<template>
	<!-- 规格-模态层弹窗 -->
	<view class="popup spec" :class="specClass" @touchmove.stop.prevent="">
		<!-- 遮罩层 -->
		<view class="mask" @tap="toggleSpec"></view>
		<view class="layer">
			<view class="sku-info flex-center">
				<view class="sku-photo">
					<image :src="selectshop.pic || initPhoto" mode="aspectFill"></image>
				</view>
				<view class="sku-right flex-column-between">
					<view class="sku-closed"><image class="icon-closed img-size-repeat" @tap="toggleSpec"></image></view>
					<view class="flex-column">
						<text class="sku-price font40 fontb">¥{{selectshop.price || initPrice}}</text>
						<text class="font26 color999">库存{{selectshop.stock || initSku}}件</text>
					</view>
				</view>
			</view>
			<scroll-view scroll-y class="sku-content">
				<view class="flex-column" v-for="(item, index1) in specifications" :key="index1">
					<text class="sku-title font28 color333">{{ item.name }}</text>
					<view class="flex-wrap">
						<view class="sku-attr font26 color333"
							@tap="skuClick(item_value, index1, $event, index2)"
							v-for="(item_value, index2) in item.item"
							:key="index2"
							:class="[item_value.ishow ? '' : 'sku-dis', subIndex[index1] == index2 ? 'sku-active' : '']">
							{{ item_value.name }}
						</view>
					</view>
				</view>
				<view class="sku-num flex-center-between" v-show="optype !== 'shopping'">
					<text class="font28 color333">购买数量</text>
					<uni-number-box v-model="selectNum" :min="1" :max="selectshop.stock || initSku" :disabled="canCount"></uni-number-box>
				</view>
			</scroll-view>
			<view class="sku-btn flex-center-center">
				<button class="btn-ok font34 colorfff" @tap="add(optype === 'cat'? 'cat' : 'buy')" v-show="optype === 'cat' || optype === 'buy'">确认</button>
				<button class="btn-join font34 colorfff" @tap="add('cat')" v-show="optype === 'select'">加入购物车</button>
				<button class="btn-buy font34 colorfff" @tap="add('buy')" v-show="optype === 'select'">立即购买</button>
				<button class="btn-join font34 colorfff" @tap="add('shopping')" v-show="optype === 'shopping'">确定</button>
				<button class="btn-buy font34 colorfff" @tap="navToTabPage" v-show="optype === 'shopping'">查看详情</button>
			</view>
		</view>
	</view>
</template>

<script>
import Api from '@/common/api'
import uniNumberBox from "@/components/uni-number-box/uni-number-box"
import { mapState } from 'vuex'
export default {
	data() {
		return {
			specClass: 'none',
			specifications: [], //spu规格列表
			difference: [], //sku列表
			shopItemInfo: {}, //存放要和选中的值进行匹配的数据
			selectArr: [], //存放被选中的值
			subIndex: [], //是否选中 因为不确定是多规格还是但规格，所以这里定义数组来判断
			selectshop: {}, //存放最后选中的商品
			selectNum: 1 ,//选中数量
			initPhoto: '', // 初始图片
			initPrice: '', // 初始价格
			initSku: 0, // 初始库存
		}
	},
	methods: {
		// 页面跳转
		navToTabPage() {
			this.toggleSpec()
			uni.navigateTo({ url: '/pages/product/product?id=' + this.id })
		},
		// 初始化数据
		init() {
			this.specifications = [] //spu规格列表
			this.difference = [] //sku列表
			this.shopItemInfo = {} //存放要和选中的值进行匹配的数据
			this.selectArr = [] //存放被选中的值
			this.subIndex = [] //是否选中 因为不确定是多规格还是但规格，所以这里定义数组来判断
			this.selectshop = {} //存放最后选中的商品
			this.initPhoto = '' // 初始图片
			this.initPrice = '' // 初始价格
			this.initSku = 0 // 初始库存
		},
		// 加入购物车或者立即购买
		async add(type) {
			if (!uni.getStorageSync('token')) {
				uni.navigateTo({
					url: '/pages/public/login'
				})
				return
			}
			let flag = this.selectArr.some((item, index) => {
				if(item === '') {
					this.$api.msg('请选择 ' + this.specifications[index].name,)
					return true
				}
			})
			if(type === 'cat') { // 加入购物车
				// 全选
				if(!flag) {
					let res = await Api.apiCall('post', Api.order.addCart, {
						goodsId: this.id,
						skuId: this.selectshop.id,
						total: this.selectNum,
					})
					if(res) {
						this.$api.msg('添加成功，到购物车查看')
						this.toggleSpec()
					}
				}
			}else if(type === 'buy') { // 立即购买
				// 全选
				if(!flag) {
					let param = {
						total: this.selectNum,
						type: 1,
						skuId: this.selectshop.id,
						goodsId: this.id,
					}
					let res = await Api.apiCall('get', Api.order.addOrder, param, true)
					if(res) {
						// 页面跳转
						this.$emit('sumbit', res, param)
					}
					this.toggleSpec()
				}
			}else if(type === 'shopping') { // 购物车的确认
				// 全选
				if(!flag) {
					this.toggleSpec()
					this.$emit('shoppingok')
				}
			}
		},
		//规格弹窗开关
		toggleSpec() {
			if (this.specClass === 'show') {
				this.specClass = 'hide';
				setTimeout(() => {
					this.specClass = 'none';
				}, 250);
			} else if (this.specClass === 'none') {
				this.specClass = 'show';
			}
		},
		skuClick(value, index1, event, index2) {
			if (value.ishow) {
				if (this.selectArr[index1] != value.name) {
					this.$set(this.selectArr, index1, value.name);
					this.$set(this.subIndex, index1, index2);
				} else {
					this.$set(this.selectArr, index1, '');
					this.$set(this.subIndex, index1, -1);
				}
				this.checkInpath(index1);
				// console.log(this.selectArr)
				this.selectNum = 1
				//如果全部选完
				if (this.selectArr.every(item => item != '')) {
					// console.log(this.selectArr)
					// console.log(this.shopItemInfo)
					this.selectshop = this.shopItemInfo[this.selectArr]
					this.$emit('input', this.selectshop)
				}else {
					this.selectshop = {}
					this.$emit('input', {})
				}
			}
		},
		// 处理波段价格和总库存、库存为0剔除
		handleInitData() {
			let del = []
			let arr = []
			this.difference.map((item, index) => {
				if(item.stock === 0) {
					del.push(index)
				}else {
					arr.push(item.price)
				}
				this.initSku += item.stock
			})
			if(this.difference.length) {
				this.initPhoto = this.difference[0].pic
			}
			let a = arr.sort()
			let min = a[0]
			let max = a[a.length-1]
			this.initPrice = min == max ? min : min + '-' + max
			// 库存为0的从该数组剔除
			del.reverse().map(item => {
				this.difference.splice(item, 1)
			})
		},
		checkInpath(clickIndex) {
			// console.time('筛选可选路径需要的时间是');
			//循环所有属性判断哪些属性可选
			//当前选中的兄弟节点和已选中属性不需要循环
		
			for (let i = 0, len = this.specifications.length; i < len; i++) {
				if (i == clickIndex) {
					continue;
				}
				let len2 = this.specifications[i].item.length;
				for (let j = 0; j < len2; j++) {
					if (this.subIndex[i] != -1 && j == this.subIndex[i]) {
						continue;
					}
					let choosed_copy = [...this.selectArr];
					// console.log(choosed_copy)
					this.$set(choosed_copy, i, this.specifications[i].item[j].name);
					let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
					// console.log(choosed_copy2)
					// console.log(this.shopItemInfo)
					if (this.shopItemInfo.hasOwnProperty(choosed_copy2)) {
						if(this.shopItemInfo[choosed_copy2].stock === 0) { // handleInitData已经过滤库存为0，第二层过滤库存为0
							this.$set(this.specifications[i].item[j], 'ishow', false);
						}else {
							this.$set(this.specifications[i].item[j], 'ishow', true);
						}
					} else {
						this.$set(this.specifications[i].item[j], 'ishow', false);
					}
				}
			}
			// console.log(this.specifications)
			// console.timeEnd('筛选可选路径需要的时间是');
		},
		checkItem() {
			// console.time('计算有多小种可选路径需要的时间是');
			//计算有多小种可选路径
			let result = this.difference.reduce(
				(arrs, items) => {
					return arrs.concat(
						items.difference.reduce(
							(arr, item) => {
								return arr.concat(
									arr.map(item2 => {
										//利用对象属性的唯一性实现二维数组去重
										if (!this.shopItemInfo.hasOwnProperty([...item2, item])) {
											this.shopItemInfo[[...item2, item]] = items;
										}
										return [...item2, item];
									})
								);
							},
							[[]]
						)
					);
				},
				[[]]
			);
			// console.timeEnd('计算有多小种可选路径需要的时间是');
		},
	},
	// sku列表、spu规格列表、选中的数据、(select选规格 cat加入购物车 buy立即购买 shopping购物车)、商品id、attrid 规格id用于购物车
	props: ['skuStockList', 'productAttributeValueList', 'value', 'optype', 'id', 'attrid'],
	watch: {
		skuStockList(value) {
			if(this.attrid) { this.init() }
			this.difference = [...value]
			this.handleInitData()
		},
		productAttributeValueList(value) {
			this.specifications = [...value]
			this.specifications.map(item => {
				this.selectArr.push('')
				this.subIndex.push(-1)
			});
			this.checkItem(); //计算sku里面规格形成路径
			this.checkInpath(-1); //传-1是为了不跳过循环
		},
		specClass(value) {
			// 监听打开规格选择
			if(value === 'show') {
				
				// this.difference = [...this.skuStockList]
				// this.handleInitData()
				// this.specifications = [...this.productAttributeValueList]
				// this.specifications.map(item => {
				// 	this.selectArr.push('')
				// 	this.subIndex.push(-1)
				// });
				// this.checkItem(); //计算sku里面规格形成路径
				// this.checkInpath(-1); //传-1是为了不跳过循环
				// 购物车初始值
				if(this.attrid) {
					this.subIndex = []
					this.difference.map(item => {
						if(this.attrid === item.id) {
							this.selectshop = item
						}
					})
					this.selectArr = [...this.selectshop.difference]
					this.selectArr.map((item, index) => {
						this.specifications[index].item.map((val, idx) => {
							if(item === val.name) {
								this.subIndex.push(idx)
							}
						})
					})
				}
			}
		},
	},
	components:{
		uniNumberBox
	},
	computed: {
		...mapState(['hasLogin']),
		canCount() {
			return this.subIndex.some(item => item === -1)
		}
	},
}
</script>

<style lang="scss">
/*  弹出层 */
.popup {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	z-index: 999;

	&.show {
		display: block;
		.mask {
			animation: showPopup 0.2s linear both;
		}
		.layer {
			animation: showLayer 0.2s linear both;
		}
	}
	&.hide {
		.mask {
			animation: hidePopup 0.2s linear both;
		}
		.layer {
			animation: hideLayer 0.2s linear both;
		}
	}
	&.none {
		display: none;
	}
	.mask {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
		background-color: rgba(0, 0, 0, 0.4);
	}
	.layer {
		position: fixed;
		z-index: 99;
		bottom: 0;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		background-color: #fff;
		.sku-info {
			height: 277rpx;
			padding: 30rpx 30rpx 27rpx;
			border-bottom: 1rpx solid #eee;
			.sku-photo {
				width: 220rpx;
				height: 220rpx;
				margin-right: 30rpx;
				image {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}
			}
			.sku-right {
				width: calc(100% - 250rpx);
				height: 100%;
				.sku-closed {
					text-align: right;
					.icon-closed {
						width: 50rpx;
						height: 50rpx;
						background-image: url('/static/image/closeattr.png');
					}
				}
				.sku-price {
					color: #F24724;
					margin-bottom: 8rpx;
				}
			}
		}
		
		.sku-content {
			width: 100%;
			height: 720rpx;
			padding: 40rpx 30rpx;
			.flex-column {
				margin-bottom: 20rpx;
				.sku-title {
					margin-bottom: 30rpx;
				}
				.sku-attr {
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					padding: 13rpx 40rpx;
					border-radius: 32rpx;
					background-color: #EEE;
					border: 1rpx solid #EEE;
				}
				.sku-dis {
					background-color: #F8F8F8;
					border: 1rpx solid #F8F8F8;
					color: #CCC;
				}
				.sku-active {
					background-color: rgba(240, 67, 31, 0.09);
					border: 1rpx solid #F0431F;
					color: #F0431F;
				}
			}
			.sku-num {
				width: 100%;
				height: 60rpx;
				line-height: 60rpx;
				margin-top: 42rpx;
			}
		}
		
		.sku-btn {
			width: 100%;
			height: 140rpx;
			.btn-ok {
				width: 560rpx;
				height: 80rpx;
				background-color: #C84739;
				border-radius: 50rpx;
				&::after {
					border: 0;
				}
			}
			.btn-join,
			.btn-buy {
				width: 330rpx;
				height: 80rpx;
				border-radius: 50rpx;
				&::after {
					border: 0;
				}
			}
			.btn-join {
				background:linear-gradient(304deg,rgba(232,106,25,1) 0%,rgba(241,170,36,1) 100%);
			}
			.btn-buy {
				background-color: #C84739;
			}
		}
	}
	@keyframes showPopup {
		0% {
			opacity: 0;
		}
		100% {
			opacity: 1;
		}
	}
	@keyframes hidePopup {
		0% {
			opacity: 1;
		}
		100% {
			opacity: 0;
		}
	}
	@keyframes showLayer {
		0% {
			transform: translateY(120%);
		}
		100% {
			transform: translateY(0%);
		}
	}
	@keyframes hideLayer {
		0% {
			transform: translateY(0);
		}
		100% {
			transform: translateY(120%);
		}
	}
}
</style>
